package com.lgl.mes.trace.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lgl.mes.basedata.entity.SpTableManager;
import com.lgl.mes.common.Result;
import com.lgl.mes.common.util.log.SysLogAspect;
import com.lgl.mes.order.orderMaterial.entity.SpOrderMaterial;
import com.lgl.mes.order.orderMaterial.mapper.SpOrderMaterialMapper;
import com.lgl.mes.order.orderMaterial.service.ISpOrderMaterialService;
import com.lgl.mes.product.entity.SpProduct;
import com.lgl.mes.product.request.spProductReq;
import com.lgl.mes.technology.entity.SpFlow;
import com.lgl.mes.trace.entity.SpMaterialTrace;
import com.lgl.mes.trace.request.spTraceReq;
import com.lgl.mes.trace.service.ISpMaterialTraceService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import com.lgl.mes.common.BaseController;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 75039960@qq.com
 * @since 2022-09-27
 */
@Controller
@RequestMapping("/trace")
public class SpMaterialTraceController extends BaseController {

    @Autowired
   public ISpMaterialTraceService iSpMaterialTraceService ;

    @Autowired
    public ISpOrderMaterialService iSpOrderMaterialService ;

    @Autowired
    SysLogAspect SysLogAspect;


        @ApiOperation("列表界面UI")
    @ApiImplicitParams({@ApiImplicitParam(name = "model", value = "模型", defaultValue = "模型")})
    @GetMapping("/list-ui")
    public String listUI(Model model) {

        return "trace/list";
    }


    /**
     * 物料管理修改界面
     *
     * @param record 平台表对象
     * @return 更改界面
     */
    @ApiOperation("修改界面")
    @GetMapping("/add-or-update-ui")
    public String addOrUpdateUI(Model model, SpTableManager record) {
        if (StringUtils.isNotEmpty(record.getId())) {
            SpMaterialTrace spProduct = iSpMaterialTraceService.getById(record.getId());
            model.addAttribute("result", spProduct);
        }
        return "trace/addOrUpdate";
    }



    /**
     * 产品管理界面分页查询
     *
     * @param req 请求参数
     * @return Result 执行结果
     */
    @ApiOperation("分页查询")
    @ApiImplicitParams({@ApiImplicitParam(name = "req", value = "请求参数", defaultValue = "请求参数")})
    @PostMapping("/page")
    @ResponseBody
    public Result page(spTraceReq req) {
        QueryWrapper<SpMaterialTrace> queryWrapper =new QueryWrapper();
        //QueryWrapper queryWrapper =new QueryWrapper();


        if (StringUtils.isNotEmpty(req.getProductIdLike()))
        {
            queryWrapper.like("product_id",req.getProductIdLike());
        }


        //产品序列号
        if (StringUtils.isNotEmpty(req.getProductSerialLike()))
        {
            queryWrapper.like("product_serial",req.getProductSerialLike());
        }

        // 物料编码
        if (StringUtils.isNotEmpty(req.getMaterialLike()))
        {
            queryWrapper.like("material",req.getMaterialLike());
        }

        if (StringUtils.isNotEmpty(req.getMaterialBatchNoLike()))
        {
            queryWrapper.like("material_batch_no",req.getMaterialBatchNoLike());
        }



        if (StringUtils.isNotEmpty(req.getqualityLike()))
        {
            queryWrapper.like("quality",req.getqualityLike());
        }

        /*if (StringUtils.isNotEmpty(req.getQrcodeLike()))
        {
             queryWrapper.like("qrcode",req.getQrcodeLike());
        }
*/

        if (req.getCreateTime1() !=null && !req.getCreateTime1().isEmpty())
        {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate localDate= LocalDate.parse(req.getCreateTime1(), formatter);
            //queryWrapper.ge("createTime",ld);
            queryWrapper.apply("UNIX_TIMESTAMP(create_time) >= UNIX_TIMESTAMP('" + localDate + "')");
        }


        if (req.getCreateTime2() !=null && !req.getCreateTime2().isEmpty())
        {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate localDate= LocalDate.parse(req.getCreateTime2(), formatter);
            queryWrapper.apply("UNIX_TIMESTAMP(create_time) <= UNIX_TIMESTAMP('" + localDate + "')");
        }

        IPage result = iSpMaterialTraceService.page(req,queryWrapper);
        return Result.success(result);
    }



    @ApiOperation("修改、新增")
    @PostMapping("/add-or-update")
    @ResponseBody
    public Result addOrUpdate(SpMaterialTrace record) {

        if(record==null || record.getProductId()==null ||record.getProductId().isEmpty())
        {
            return Result.failure("没有数据！");
        }

            iSpMaterialTraceService.saveOrUpdate(record);

            return Result.success();
    }


    /**
     * 删除产品信息
     *
     * @param req 请求参数
     * @return Result 执行结果
     */
    @ApiOperation("删除信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "req", value = "产品实体", defaultValue = "产品实体")})
    @PostMapping("/delete")
    @ResponseBody
    public Result deleteByTableNameId(SpMaterialTrace req) throws Exception {
        iSpMaterialTraceService.removeById(req.getId());
        return Result.success();
    }



    @ApiOperation("批量删除信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "ids", value = "product ids", defaultValue = "product ids")})
    @PostMapping("/batchDelete")
    @ResponseBody
    public Result batchDelete( String  ids) throws Exception {

        String[] tempList = ids.split(",");
        for (String id  :  tempList)
        {
            iSpMaterialTraceService.removeById(id);
        }

        //iSpBomService.removeByIds(list);

        return Result.success();
    }

    /*
      请使用  xlsx 格式

      js  文件    替换了 “请求上传接口出现异常"  --->  上传完毕

    */
    @PostMapping("/batchImport")
    public Result  excelExport(@RequestParam MultipartFile file){

        String resMsg ="";

        try {
            resMsg = iSpMaterialTraceService.LocalImport(file);
            //if (resMsg.isEmpty() || resMsg.equals(""))
              //  resMsg = "导入成功";
        }
        catch (Exception e) {
            resMsg = e.getMessage();
            e.printStackTrace();
        }

        SysLogAspect.saveSysLog("批量导产品和物料溯源信息","batchImport", file.getOriginalFilename(), resMsg);
        return  Result.success( resMsg) ;
    }


}
